package com.vvlive.caibao.smartcity.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ListView;

import com.vvlive.caibao.smartcity.adapter.MeetingsAdapter;
import com.vvlive.caibao.smartcity.base.BaseFragment;
import com.vvlive.caibao.smartcity.base.CalendarViews;
import com.vvlive.caibao.smartcity.base.MeetingsListInterface;
import com.vvlive.caibao.smartcity.bean.Dept;
import com.vvlive.caibao.smartcity.bean.MeetingByMonth;
import com.vvlive.caibao.smartcity.bean.MeetingRoom;
import com.vvlive.caibao.smartcity.bean.NewMeetingInfo;
import com.vvlive.caibao.smartcity.ui.MeetingDetailsActivity;
import com.vvlive.caibao.smartcity.ui.OrderOneMeetingActivity;
import com.vvlive.caibao.smartcity.utils.MeetingsController;
import com.wefika.calendar.CollapseCalendarView;
import com.wefika.calendar.manager.CalendarManager;

import org.joda.time.LocalDate;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import smartcity.vvlive.caibao.com.smartc.R;

/**
 * Created by zhj on 2015/10/15.
 * 会议的日历月视图
 */
public class MonthViewFragment extends BaseFragment implements CalendarViews {

    /**
     * 日历控件
     */
    private CollapseCalendarView mCalendarView;
    private CalendarManager mCalendarManager;
    private ListView mListView;
    private Calendar calendar;
    private MeetingsListInterface mListInterface;
    private MeetingsCallBack mCallBack;
    private Dept mDept;
    private MeetingRoom mRoom;
    private OnRefreshListener mRefresh;

    public MonthViewFragment() {
        mCalendarManager = new CalendarManager(
                                                      LocalDate.now(),
                                                      CalendarManager.State.MONTH,
                                                      LocalDate.now(),
                                                      LocalDate.now().plusYears(1));
        calendar = Calendar.getInstance();
        mCallBack = new MeetingsCallBack();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        if (activity instanceof MeetingsListInterface) {
            mListInterface = (MeetingsListInterface) activity;
        }
    }

    @Override
    public int getContentRes() {
        return R.layout.fragment_month_view;
    }

    @Override
    public void initFragment() {

        mCalendarView = findView(R.id.meeting_calendar);
        mCalendarView.init(mCalendarManager);
        mCalendarView.setListener(mCallBack);

        mListView = findView(R.id.meeting_list);
        mListView.setEmptyView(getEmptyView());
        mListInterface.setOnMeetingsPreparedListener(mCallBack, calendar, 1);
    }

    private Intent mIntent;

    /**
     * 获取ListView的emptyView
     *
     * @return
     */
    private View getEmptyView() {
        View emptyView = LayoutInflater.from(getActivity()).inflate(R.layout.view_meeting_empty, null);
        emptyView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        emptyView.findViewById(R.id.order_btn).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mIntent == null) {
                    mIntent = new Intent();
                }
                mIntent.setClass(getActivity(), OrderOneMeetingActivity.class);
                Bundle data = new Bundle();
                NewMeetingInfo newMeetingInfo = new NewMeetingInfo();
                if (mDept != null) {
                    newMeetingInfo.setDept(new String[]{mDept.getDeptid(), mDept.getDeptname()});
                }
                if (mRoom != null) {
                    newMeetingInfo.setRoom(new String[]{mRoom.getRoomid(), mRoom.getRoom()});
                }
                newMeetingInfo.setStartTime(getDate().getTimeInMillis());
                data.putSerializable(PagerAllMeetingsFragment.NEW_MEETING_INFO_KEY, newMeetingInfo);
                mIntent.putExtras(data);
                startActivityForResult(mIntent, PagerAllMeetingsFragment.ORDER_ONE_MEETING_REQUEST_CODE);
            }
        });
        ViewGroup parentView = (ViewGroup) mListView.getParent();
        parentView.addView(emptyView, 2);
        return emptyView;
    }

    /**
     * 操作会议的回调函数
     */
    final class MeetingsCallBack implements MeetingsListInterface.OnMeetingsPreparedListener,
                                                    CollapseCalendarView.OnDateSelect, AdapterView.OnItemClickListener,
                                                    MeetingsListInterface.OnMeetingsRefreshListener {

        private ArrayList<MeetingByMonth> mMeetings;
        private ArrayList<MeetingByMonth> mStorage;
        private ArrayList<MeetingByMonth> mInfo;
        private MeetingsAdapter mAdapter;

        public MeetingsCallBack() {
            mMeetings = new ArrayList<>();
            mStorage = new ArrayList<>();
        }

        @Override
        public void onGetMeetings(List<MeetingByMonth> meetingBeans) {
            MeetingsController.Sort.orderByStartTimeDesc2(meetingBeans);
            mMeetings = (ArrayList<MeetingByMonth>) meetingBeans;
            mStorage = (ArrayList<MeetingByMonth>) mMeetings.clone();
            mInfo = (ArrayList<MeetingByMonth>) mMeetings.clone();
            mAdapter = new MeetingsAdapter(getActivity(), mInfo);
            mListView.setAdapter(mAdapter);
            mListView.setOnItemClickListener(this);
            Date date = new Date();
            filterMeetingByDate(date.getMonth() + 1, date.getDate());
        }

        @Override
        public void onDateSelected(LocalDate date) {
            calendar.set(Calendar.YEAR, date.getYear());
            calendar.set(Calendar.MONTH, date.getMonthOfYear() - 1);
            calendar.set(Calendar.DAY_OF_MONTH, date.getDayOfMonth());
            filterMeetingByDate(date.getMonthOfYear(), date.getDayOfMonth());
        }

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Intent intent = new Intent(getActivity(), MeetingDetailsActivity.class);
            Bundle bundle = new Bundle();
            bundle.putSerializable(MeetingDetailsActivity.DETAILS_KEY, mInfo.get(position));
            intent.putExtras(bundle);
            startActivity(intent);
        }

        public ArrayList<MeetingByMonth> getMeetings() {
            return mMeetings;
        }

        public ArrayList<MeetingByMonth> getStorage() {
            return mStorage;
        }

        public ArrayList<MeetingByMonth> getInfo() {
            return mInfo;
        }

        public MeetingsAdapter getAdapter() {
            return mAdapter;
        }

        /**
         * 添加一个条目（用途忘了。。。）
         *
         * @param meetingByMonth
         */
        public void addOneItem(MeetingByMonth meetingByMonth) {
            mStorage.add(meetingByMonth);
            mInfo.add(meetingByMonth);
            mAdapter.notifyDataSetChanged();
        }

        @Override
        public void onFailure(int code, String msg) {
            if (mRefresh != null) {
                mRefresh.onFinish(CalendarViews.REFRESH_FAILURE);
            }
        }
    }

    /**
     * 根据日期过滤会议
     *
     * @param month
     * @param dayOfMonth
     */
    private void filterMeetingByDate(int month, int dayOfMonth) {
        ArrayList<MeetingByMonth> info = mCallBack.getInfo();
        ArrayList<MeetingByMonth> storage = mCallBack.getStorage();
        if (info != null) {
            info.clear();
            for (MeetingByMonth bean : storage) {
                long millis = MeetingsController.getStartDateTimeInMillis(bean.getTime());
                if (isTheSameDay(new Date(millis), month, dayOfMonth)) {
                    info.add(bean);
                }
            }
            mCallBack.getAdapter().notifyDataSetChanged();
        }
        if (mRefresh != null) {
            mRefresh.onFinish(CalendarViews.REFRESH_SUCCESS);
        }
    }

    /**
     * 是否是同一天
     *
     * @param now
     * @param month
     * @param dayOfMonth
     * @return
     */
    private boolean isTheSameDay(Date now, int month, int dayOfMonth) {
        return now.getMonth() + 1 == month && now.getDate() == dayOfMonth;
    }

    @Override
    public String getHeaderText() {
        return mCalendarManager.getHeaderText();
    }

    @Override
    public void prev() {
        mCalendarManager.prev();
        mCalendarView.populateLayout();
        changeMonth(-1);
    }

    @Override
    public void next() {
        mCalendarManager.next();
        mCalendarView.populateLayout();
        changeMonth(1);
    }

    @Override
    public Calendar getDate() {
        return calendar;
    }

    @Override
    public void onSelectRoom(Dept dept, MeetingRoom[] meetingRoom) {
        mDept = dept;
        mRoom = meetingRoom[0];
    }

    @Override
    public void onResult(int requestCode, int resultCode, Intent data) {
        mListInterface.refreshMeetings(mCallBack);
    }

    @Override
    public void onRefresh(OnRefreshListener onRefreshListener) {
        mRefresh = onRefreshListener;
        mListInterface.setOnMeetingsPreparedListener(mCallBack, calendar, 1);
    }

    /**
     * 改变月份
     *
     * @param month
     */
    private void changeMonth(int month) {
        calendar.set(Calendar.MONTH, calendar.get(Calendar.MONTH) + month);
        mListInterface.setOnMeetingsPreparedListener(mCallBack, calendar, 1);
    }
}
